package com.hyjx.framework.component.customquery;

import com.alibaba.fastjson.JSON;
import com.hyjx.framework.common.CommonUtil;
import com.hyjx.framework.common.util.SpringBeanUtil;
import com.hyjx.framework.orm.dao.IBaseDao;
import com.hyjx.framework.orm.dao.Pager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义查询服务实现类
 */
@Service
@Transactional
public class CustomQueryServiceImpl implements CustomQueryService {
    
    @Resource
    private IBaseDao dao;
    
    @Override
    public String queryList(CustomQueryModel model) {
        Pager pager = dao.getPager(model.getModuleName() + ".queryList", model.getModuleName() + ".queryCount", model);
        
        return CommonUtil.getPageJsonStr(pager);
    }
    
    @Override
    public boolean add(CustomQueryModel model) {
        return dao.addObject(model.getModuleName() + ".insert", model);
    }
    
    @Override
    public CustomQueryModel getInfoById(String s) {
        return (CustomQueryModel) dao.queryObject((new CustomQueryModel()).getModuleName() + ".getInfoById", s);
    }
    
    @Override
    public int edit(CustomQueryModel model) {
        return dao.updateObject(model.getModuleName() + ".update", model);
    }
    
    @Override
    public int delete(String ids) {
        String[] id_array = ids.split(",");
        int num = 0;
        for (String id : id_array) {
            dao.deleteObject((new CustomQueryModel()).getModuleName() + ".delete", id);
            num++;
        }
        return num;
    }
    
    @Override
    public List<Map<String, String>> getColumns(String sql) {
        if (StringUtils.isEmpty(sql) || sql.toLowerCase().indexOf("select") == -1 || sql.toLowerCase().indexOf("from") == -1) {
            return null;
        }
        
        DataSource dataSource = (DataSource) SpringBeanUtil.getBean("dataSource");
        Connection conn = null;
        ResultSet resultSet = null;
        ResultSetMetaData resultSetMetaData = null;
        List<Map<String, String>> columns = new ArrayList<Map<String, String>>();
        Map<String, String> column = null;
        try {
            conn = dataSource.getConnection();
            resultSet = conn.createStatement().executeQuery(sql);
            resultSetMetaData = resultSet.getMetaData();
            for (int colNum = 0; colNum < resultSetMetaData.getColumnCount(); colNum++) {
                column = new HashMap<String, String>();
                column.put("COLUMN_NAME", resultSetMetaData.getColumnName(colNum + 1).toUpperCase());
                columns.add(column);
            }
        } catch (SQLException e) {
        } finally {
            try {
                if (resultSet != null) resultSet.close();
            } catch (SQLException e1) {
            }
            try {
                conn.close();
            } catch (SQLException e1) {
            }
        }
        return columns;
    }
    
    @Override
    public String getFileds(CustomQueryModel model) {
        
        List<Map<String, String>> cols = getColumns(model.getQuery_sql());
        for (Map<String, String> map : cols) {
        
        }
        return null;
    }
    
    @Override
    public List<ListConfig> getListConfig(CustomQueryModel model) {
        return null;
    }
    
    @Override
    public PageConfig getPageConfig(CustomQueryModel model) {
        PageConfig pageConfig = new PageConfig();
        List<Map<String, String>> cols = null;
        cols = getColumns(model.getQuery_sql());
        if (cols == null) {
            return null;
        }
        List<ListConfig> listConfigs = new ArrayList<ListConfig>();
        for (Map<String, String> map : cols) {
            ListConfig listConfig = new ListConfig();
            listConfig.setColumnName(map.get("COLUMN_NAME"));
            listConfigs.add(listConfig);
        }
        pageConfig.setListConfigList(listConfigs);
        return pageConfig;
    }
    
    @Override
    public String getPageHtml(CustomQueryModel model) {
        
        return null;
    }
    
    @Override
    public String queryMapJSON(String sql) {
        CustomQueryModel model = new CustomQueryModel();
        return dao.getPageJsonStr(model.getModuleName() + ".querymap", model.getModuleName() + ".querymapcount", sql);
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public List<Map<String, String>> queryMap(String sql) {
        return (List<Map<String, String>>) dao.queryObjectList((new CustomQueryModel()).getModuleName() + ".querymap", sql);
    }
    
    @Override
    public void executeSql(String sql) {
        dao.executeSql(sql);
    }
    
    @Override
    public void inserttpl(CustomQueryTplModel cqt) {
        dao.addObject(cqt.getModuleName() + ".inserttpl", cqt);
    }
    
    @Override
    public void edittpl(CustomQueryTplModel cqt) {
        dao.updateObject(cqt.getModuleName() + ".updatettpl", cqt);
    }
    
    @Override
    public String getTplData(CustomQueryTplModel cqt) {
        List<CustomQueryTplModel> list = dao.queryObjectList(cqt.getModuleName() + ".gettpldata", cqt);
        return JSON.toJSONString(list);
    }
    
    @Override
    public String getTplById(CustomQueryTplModel cqt) {
        return (String) dao.queryObject(cqt.getModuleName() + ".gettplbyid", cqt);
    }
    
    @Override
    public int delTpl(CustomQueryTplModel cqt) {
        return dao.deleteObject(cqt.getModuleName() + ".deltpl", cqt);
    }
}